/*
 * @Description: 绘图模式下功能模块-线
 * @Date: 2022-01-20 16:02:07
 * @Author: yeming
 */

// 1、单线：作为独立线段使用，每次均会创建独有的Feature，eg：目标引导线、接地线等
// 2、多线：初始化生成对应geom和Feature，后续不再生成geom和Feature，只会在该geom内添加经纬度数据，eg：航线、轨迹线等

import { transform, fromLonLat, toLonLat } from 'ol/proj.js'
import { getDistance } from 'ol/sphere'
import OlFeature from 'ol/Feature'
import OlGeomLineString from 'ol/geom/LineString'
import { setOlStyleSolidLine, setOlStyleDashLine } from '../../../common/olStyle.js'
// 地球半径km
const EARTH_RADIUS = 6378.137
// 默认轨迹线颜色（蓝色）
const DEFAULT_LINE = { 'fillColor': '#FAB00D', 'strokeColor': 'rgba(0, 153, 255, 1)', 'strokeWidth': 2, 'dash': [10, 6] }
// 默认引导线颜色
const DEFAULT_GUIDE_LINE = { 'fillColor': 'rgba(0, 153, 255, 1)', 'strokeColor': 'rgba(0, 153, 255, 1)', 'strokeWidth': 2, 'dash': [10, 6] }

class Line3d {
  constructor(entities, id, style, isDash = false, clampToGround = false) {
    let customStyle = {}
    if (style === null || JSON.stringify(style) == "{}") customStyle = DEFAULT_LINE
    else customStyle = style

    let that = this
    this.entities = entities
    this.positions = null
    // this.isDash = isDash || false
    this.options = {
      id: id, // 创建和2d线相同sessionId的entity,
      name: 'Line3d_' + id,
      show: true
    }
    if (isDash) {
      this.options.polyline = {
        material: new Cesium.PolylineDashMaterialProperty({
          color: new Cesium.Color.fromCssColorString(customStyle.fillColor),
          dashLength: 20 // 短划线长度
        }),
        width: customStyle.strokeWidth,
        clampToGround: clampToGround,
        positions: new Cesium.CallbackProperty(function () { // 实时更新 CallbackProperty 第一个参数为回调函数
          return that.positions
        }, false)
      }
    } else {
      this.options.polyline = {
        material: new Cesium.Color.fromCssColorString(customStyle.fillColor),
        width: customStyle.strokeWidth,
        clampToGround: clampToGround,
        positions: new Cesium.CallbackProperty(function () { // 实时更新 CallbackProperty 第一个参数为回调函数
          return that.positions
        }, false)
      }
    }
    this.entity = this.entities.add(this.options)
  }
}

class Line {
  constructor(ol2d, ol3d, vectorSource) {
    this.ol2d = ol2d
    this.ol3d = ol3d
    this.map2d = ol2d.map2d // 2d地图
    this.entities = ol3d.entities
    this.vectorSource = vectorSource // 矢量标注的数据源 addFeature(), getFeatures(), removeFeature()

    this.dynamicTrackLine = null // 动态依次添加的轨迹线
    this.singleAirLine = null
    this.guideLine = null
    this.feature = null
  }

  /**
   * @desc: 添加单线，仅作为独立线段使用（如：目标引导线）默认2/3d独立渲染
   * @param {Number} sessionId
   * @param {Array} latlng1 首经纬度
   * @param {Array} latlng2 尾经纬度
   * @param {Boolean} isDash 是否虚线
   * @param {Object} style 线样式
   */
  addSingleLine (sessionId, latlng1, latlng2, isDash = false, style) {
    style = style && style != '' ? style : DEFAULT_LINE

    let feature = new OlFeature({
      id: sessionId,
      sessionId: sessionId,
      latlng1: latlng1,
      latlng2: latlng2,
      style: style,
      geometry: new OlGeomLineString([latlng1, latlng2]).transform("EPSG:4326", "EPSG:3857")
    })

    if (isDash) feature.setStyle(setOlStyleDashLine(style))
    else feature.setStyle(setOlStyleSolidLine(style))

    this.feature = feature
    this.vectorSource.addFeature(feature)
  }

  /**
   * @desc: 更新单线位置
   * @param {Number} sessionId
   * @param {Array} currentLatlng
   * @param {Array} nextLatlng
   * @param {Object} lineHashMap
   */
  updateSingleLine (sessionId, currentLatlng, nextLatlng, lineHashMap) {
    // 2d
    let currentSingleLine = lineHashMap.get(sessionId).item2d
    let feature = currentSingleLine.feature
    let coordinate = [fromLonLat(currentLatlng), fromLonLat(nextLatlng)]
    feature.getGeometry().setCoordinates(coordinate)

    // 3d
    let currentSingleLine3d = lineHashMap.get(sessionId).item3d
    let positions = currentSingleLine3d.positions
    positions[0] = new Cesium.Cartesian3.fromDegrees(currentLatlng[0], currentLatlng[1], currentLatlng[2])
    positions[1] = new Cesium.Cartesian3.fromDegrees(nextLatlng[0], nextLatlng[1], nextLatlng[2])
  }

  /**
   * @desc: 动态添加飞机轨迹线（每次接收一条经纬度数据）
   * @param {Number} sessionId
   * @param {Array} latlng [lon, lat, h]
   * @return {*}
   * @use: 使用示例
   */
  addTrackLine (sessionId, latlng) {
    let coordinate = [fromLonLat(latlng), fromLonLat(latlng)]
    this.dynamicTrackLine = new OlGeomLineString(coordinate)
    const feature = new OlFeature({
      rend3d: false, // 新版本轨迹线3d闪屏（2d、3d同时绘制导致的）
      id: sessionId,
      sessionId: sessionId,
      type: 'dynamicTrackLine',
      geometry: this.dynamicTrackLine
    })
    feature.setStyle(setOlStyleSolidLine({ 'fillColor': '#FAB00D', 'strokeColor': 'rgba(0, 153, 255, 1)', 'strokeWidth': 2 }))
    this.feature = feature
    this.vectorSource.addFeature(feature)
  }

  /**
   * @desc: 添加线（最新）
   * @param {Number} id
   * @param {Array} latlng [[lon, lat, h], [lon, lat, h], ......, [lon, lat, h]]
   * @param {Number} type 1-任务 2-降落
   * @param {Number} isEdit
   * @param {Object} style
   * @param {Boolean} rend3d 同步渲染3d，在拖动点时会闪屏
   * @return {*}
   * @use: 使用示例
 */
  addLine (id, latlng, type, isEdit = 1, style = DEFAULT_LINE, rend3d = false) {
    style = style != '' && style ? style : DEFAULT_LINE

    this.singleAirLine = new OlGeomLineString(latlng).transform("EPSG:4326", "EPSG:3857")
    const feature = new OlFeature({
      id: id,
      latlng: latlng,
      type: type,
      isEdit: isEdit,
      style: style,
      rend3d: rend3d,
      geometry: this.singleAirLine
    })
    feature.setStyle(setOlStyleSolidLine(style))
    this.feature = feature
    this.vectorSource.addFeature(feature)
  }

  /**
   * @desc: 添加引导线
   * @param {Number} id
   * @param {Array} latlng [[lon, lat, h], [lon, lat, h], ......, [lon, lat, h]]
   * @param {Number} type
   * @param {Object} style
   * @param {Boolean} rend3d
   * @return {*}
   * @use: 使用示例
   */
  addGuideLine (id, latlng, style, rend3d = false) {
    style = style && style != '' ? style : DEFAULT_GUIDE_LINE

    this.guideLine = new OlGeomLineString(latlng).transform("EPSG:4326", "EPSG:3857")
    const feature = new OlFeature({
      id: id,
      sessionId: id,
      latlng: latlng,
      type: 'guideLine',
      style: style,
      rend3d: rend3d,
      geometry: this.guideLine
    })
    feature.setStyle(setOlStyleDashLine(style))
    this.feature = feature
    this.vectorSource.addFeature(feature)
  }
}

export {
  Line,
  Line3d
}
